<template>
	<view class="container">
		<view class="header">
			<view class="title">添加车辆</view>
			<view class="subtitle">请填写您的车辆信息</view>
		</view>
		
		<!-- 添加车辆表单 -->
		<view class="form-container">
			<view class="form-item">
				<text class="form-label required">车牌号</text>
				<input 
					class="form-input" 
					type="text" 
					placeholder="请输入车牌号（如：京A12345）" 
					v-model="vehicleForm.plate_number"
					@blur="validatePlateNumber"
				/>
				<text class="error-tip" v-if="errors.plate_number">{{ errors.plate_number }}</text>
			</view>
			
			<view class="form-item">
				<text class="form-label required">车辆类型</text>
				<picker 
					class="form-picker" 
					:range="vehicleTypeOptions" 
					@change="handleTypeChange"
				>
					<view class="picker-value">
						{{ vehicleForm.vehicle_type || '请选择车辆类型' }}
					</view>
				</picker>
				<text class="error-tip" v-if="errors.vehicle_type">{{ errors.vehicle_type }}</text>
			</view>
			
			<view class="form-item">
				<text class="form-label">品牌</text>
				<input 
					class="form-input" 
					type="text" 
					placeholder="请输入车辆品牌" 
					v-model="vehicleForm.brand"
				/>
			</view>
			
			<view class="form-item">
				<text class="form-label">型号</text>
				<input 
					class="form-input" 
					type="text" 
					placeholder="请输入车辆型号" 
					v-model="vehicleForm.model"
				/>
			</view>
			
			<view class="form-item">
				<text class="form-label">颜色</text>
				<input 
					class="form-input" 
					type="text" 
					placeholder="请输入车辆颜色" 
					v-model="vehicleForm.color"
				/>
			</view>
		</view>
		
		<view class="tips">
			<text class="tip-text">* 带星号的为必填项</text>
			<text class="tip-text">* 添加车辆后，可以申请车位包月服务</text>
			<text class="tip-text">* 车辆绑定成功后将自动开通园区停车权限</text>
		</view>
		
		<view class="form-actions">
			<button class="cancel-btn" @click="navigateBack">取消</button>
			<button class="submit-btn" @click="submitForm" :disabled="isSubmitting">
				{{ isSubmitting ? '提交中...' : '提交' }}
			</button>
		</view>
	</view>
</template>

<script>
	import { addVehicle, checkPlateNumber } from '@/api/vehicle.js'
	
	export default {
		data() {
			return {
				vehicleForm: {
					plate_number: '',
					vehicle_type: '',
					brand: '',
					model: '',
					color: ''
				},
				vehicleTypeOptions: ['小轿车', 'SUV', '货车'],
				isSubmitting: false,
				// 当前用户信息
				currentUser: null,
				// 表单错误信息
				errors: {
					plate_number: '',
					vehicle_type: ''
				},
				// 车牌号检查状态
				plateNumberChecked: false
			}
		},
		onLoad() {
			console.log('添加车辆页面加载')
			// 获取当前用户信息
			this.getCurrentUser()
		},
		methods: {
			// 获取当前用户信息
			getCurrentUser() {
				const userInfo = uni.getStorageSync('userInfo')
				if (userInfo) {
					this.currentUser = JSON.parse(userInfo)
					console.log('当前用户信息', this.currentUser)
				}
			},
			
			// 处理车辆类型选择
			handleTypeChange(e) {
				const index = e.detail.value
				this.vehicleForm.vehicle_type = this.vehicleTypeOptions[index]
				this.errors.vehicle_type = ''
			},
			
			// 返回上一页
			navigateBack() {
				uni.navigateBack()
			},
			
			// 验证车牌号
			validatePlateNumber() {
				this.errors.plate_number = ''
				
				if (!this.vehicleForm.plate_number) {
					this.errors.plate_number = '请输入车牌号'
					return false
				}
				
				// 车牌号格式验证
				const plateRegex = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-Z0-9]{5,6}$/
				if (!plateRegex.test(this.vehicleForm.plate_number)) {
					this.errors.plate_number = '车牌号格式不正确'
					return false
				}
				
				// 检查车牌号是否已被绑定
				checkPlateNumber(this.vehicleForm.plate_number)
					.then(data => {
						this.plateNumberChecked = true
						if (!data.is_available) {
							this.errors.plate_number = '该车牌号已被绑定，请检查后重试'
							return false
						}
						return true
					})
					.catch(err => {
						console.error('验证车牌号失败', err)
						this.errors.plate_number = err.message || '验证车牌号失败'
						return false
					})
			},
			
			// 表单验证
			validateForm() {
				let isValid = true
				
				// 验证车牌号
				if (!this.vehicleForm.plate_number) {
					this.errors.plate_number = '请输入车牌号'
					isValid = false
				} else {
					// 车牌号格式验证
					const plateRegex = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-Z0-9]{5,6}$/
					if (!plateRegex.test(this.vehicleForm.plate_number)) {
						this.errors.plate_number = '车牌号格式不正确'
						isValid = false
					}
				}
				
				// 验证车辆类型
				if (!this.vehicleForm.vehicle_type) {
					this.errors.vehicle_type = '请选择车辆类型'
					isValid = false
				}
				
				return isValid
			},
			
			// 提交表单
			submitForm() {
				console.log('提交表单', this.vehicleForm)
				
				// 重置错误信息
				this.errors = {
					plate_number: '',
					vehicle_type: ''
				}
				
				if (!this.validateForm()) {
					return
				}
				
				this.isSubmitting = true
				
				// 检查登录状态
				const token = uni.getStorageSync('token')
				if (!token) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/login/login'
						})
					}, 1500)
					return
				}
				
				// 准备提交数据
				const submitData = {
					...this.vehicleForm,
					register_date: new Date().toISOString().split('T')[0]  // 当前日期，格式：YYYY-MM-DD
				}
				
				// 如果有用户ID，添加用户ID到请求数据
				if (this.currentUser && this.currentUser.user_id) {
					submitData.user_id = this.currentUser.user_id
				}
				
				// 提交表单数据
				addVehicle(submitData)
					.then(() => {
						uni.showToast({
							title: '添加成功',
							icon: 'success'
						})
						// 返回车辆列表页
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					})
					.catch(err => {
						console.error('添加车辆失败', err)
						uni.showToast({
							title: err.message || '添加失败',
							icon: 'none'
						})
					})
					.finally(() => {
						this.isSubmitting = false
					})
			}
		}
	}
</script>

<style>
	.container {
		padding: 30rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}
	
	.header {
		margin-bottom: 30rpx;
	}
	
	.title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 10rpx;
	}
	
	.subtitle {
		font-size: 26rpx;
		color: #666;
	}
	
	.form-container {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
	}
	
	.form-item {
		margin-bottom: 30rpx;
	}
	
	.form-label {
		display: block;
		font-size: 28rpx;
		color: #333;
		margin-bottom: 15rpx;
	}
	
	.required:after {
		content: ' *';
		color: #ff4d4f;
	}
	
	.form-input {
		width: 100%;
		height: 80rpx;
		background-color: #f9f9f9;
		border-radius: 8rpx;
		font-size: 28rpx;
		padding: 0 20rpx;
		box-sizing: border-box;
	}
	
	.form-picker {
		width: 100%;
		height: 80rpx;
		background-color: #f9f9f9;
		border-radius: 8rpx;
		font-size: 28rpx;
		padding: 0 20rpx;
		box-sizing: border-box;
	}
	
	.picker-value {
		height: 80rpx;
		line-height: 80rpx;
		color: #333;
	}
	
	.error-tip {
		font-size: 24rpx;
		color: #ff4d4f;
		margin-top: 8rpx;
	}
	
	.tips {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 20rpx 30rpx;
		margin-bottom: 30rpx;
	}
	
	.tip-text {
		display: block;
		font-size: 24rpx;
		color: #999;
		margin-bottom: 10rpx;
	}
	
	.form-actions {
		display: flex;
		justify-content: space-between;
		margin-top: 50rpx;
	}
	
	.cancel-btn {
		flex: 1;
		margin-right: 15rpx;
		background-color: #f5f5f5;
		color: #666;
		border: 1rpx solid #ddd;
		border-radius: 45rpx;
		font-size: 32rpx;
		padding: 20rpx 0;
	}
	
	.submit-btn {
		flex: 1;
		margin-left: 15rpx;
		background-color: #1890ff;
		color: white;
		border-radius: 45rpx;
		font-size: 32rpx;
		padding: 20rpx 0;
		border: none;
	}
	
	.submit-btn[disabled] {
		background-color: #cccccc;
		color: #ffffff;
	}
</style> 